package com.qzl.server.server;

import com.qzl.common.netty.config.ProtocolConstants;
import com.qzl.common.netty.handler.ExceptionHandler;
import com.qzl.common.netty.protocol.MessageCodec;
import com.qzl.server.handler.BusinessHandler;
import com.qzl.server.handler.ProtocolSwitchHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author: qzl
 * @date : 2025/6/23 13:29
 * @description: netty服务端
 */
@Component
@Slf4j
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        start();
    }

    public static void start() {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            new ServerBootstrap()
                    .group(boosGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
//                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            // 协议检测处理器：决定是 WebSocket 还是自定义协议
                            ch.pipeline().addLast(new ProtocolSwitchHandler());

                            ch.pipeline().addLast(new BusinessHandler());
                            // 异常处理器
                            ch.pipeline().addLast(new ExceptionHandler());
                        }

                        @Override
                        public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            log.info("客户端已连接: {}", ctx.channel().remoteAddress());
                        }
                    })
                    .bind(8848)
                    .sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boosGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
